package com.zzy.mvcframework.servlet;

import com.zzy.mvcframework.annotations.*;
import com.zzy.mvcframework.pojo.Handler;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件描述: <br>
 * 版权所有: Copyright (c) 2021/5/30<br>
 * 完成日期: 2021/5/30<br>
 *
 * @author zainzhang
 */
public class MydispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String,Object> ioc = new HashMap<String,Object>();

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        doScan(properties.getProperty("scanPackage"));

        doInstance();

        doAutowired();

        initHandlerMapping();

        System.out.println("初始化完成...");
    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doScan(String scanPackage) {
        String sacnPackage = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(sacnPackage);
        if (!pack.exists()) {
            return;
        }
        for (File file : pack.listFiles()) {
            if(file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());
            }else if(file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    private void doInstance() {
        if(classNames.size() == 0){
            return;
        }
        try{
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(MyController.class)) {
                    String simpleName = clazz.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = clazz.getDeclaredConstructor().newInstance();
                    ioc.put(lowerFirstSimpleName,o);
                }else if(clazz.isAnnotationPresent(MyService.class)) {
                    MyService annotation = clazz.getAnnotation(MyService.class);
                    String beanName = annotation.value();
                    if(!"".equals(beanName.trim())) {
                        ioc.put(beanName,clazz.getDeclaredConstructor().newInstance());
                    }else{
                        beanName = lowerFirst(clazz.getSimpleName());
                        ioc.put(beanName, clazz.getDeclaredConstructor().newInstance());
                    }
                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        ioc.put(anInterface.getName(), clazz.getDeclaredConstructor().newInstance());
                    }
                }else{
                    continue;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doAutowired() {
        if(ioc.isEmpty()) {return;}
        for(Map.Entry<String,Object> entry: ioc.entrySet()) {
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                if(!declaredField.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }
                MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);
                String beanName = annotation.value();
                if("".equals(beanName.trim())) {
                    beanName = declaredField.getType().getName();
                }
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initHandlerMapping() {
        if(ioc.isEmpty()) {return;}
        for(Map.Entry<String,Object> entry: ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(MyController.class)) {continue;}

            String baseUrl = "";
            if(clazz.isAnnotationPresent(MyRequestMapping.class)) {
                MyRequestMapping annotation = clazz.getAnnotation(MyRequestMapping.class);
                baseUrl = annotation.value();
            }
            for (Method method : clazz.getMethods()) {
                if(!method.isAnnotationPresent(MyRequestMapping.class)) {continue;}
                MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;

                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),j);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),j);
                    }
                }
                handlerMapping.add(handler);
            }
        }
    }

    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = getHandler(req);

        if(handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }

        String username = req.getParameter("username");
        Object controller = handler.getController();
        Class<?> controllerClass = controller.getClass();
        if (controllerClass.isAnnotationPresent(Security.class)) {
            Security security = controllerClass.getAnnotation(Security.class);
            String[] value = security.value();
            if (!ArrayUtils.contains(value, username)) {
                resp.getWriter().write("403 Permission denied");
                return;
            }
        }

        Method method = handler.getMethod();
        if (method.isAnnotationPresent(Security.class)) {
            Security security = method.getAnnotation(Security.class);
            String[] value = security.value();
            if (!ArrayUtils.contains(value, username)) {
                resp.getWriter().write("403 Permission denied");
                return;
            }
        }
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] paraValues = new Object[parameterTypes.length];

        Map<String, String[]> parameterMap = req.getParameterMap();
        for(Map.Entry<String,String[]> param: parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ",");
            if(!handler.getParamIndexMapping().containsKey(param.getKey())) {continue;}
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            paraValues[index] = value;
        }

        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;

        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;
        try {
            method.invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if(handlerMapping.isEmpty()){return null;}
        String url = req.getRequestURI();
        for(Handler handler: handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }
}
